package edu.nctu.csie.jichang.database.model.cell;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
 * 存放一對多 例如 一個  pk 由多個欄位組成
 * @author Jichang
 */
public class NameMap {

	private Map<String,List<NameMapCell>> map = new LinkedHashMap<String, List<NameMapCell>>();
	
	public NameMap() {
	}
	
	public Set<String> getNames(){
		return map.keySet();
	}
	
	public void addColumn(String pName,NameMapCell pColumnName){
		List<NameMapCell> tColumns = getColumns(pName);
		if(tColumns == null){
			tColumns = new ArrayList<NameMapCell>();
		}
		if(!tColumns.contains(pColumnName)){
			tColumns.add(pColumnName);
		}
		map.put(pName, tColumns);
	}

	public String getName(String pColumn){
		for (String s : map.keySet()) {
			List<NameMapCell> tColumns = map.get(s);
			for (NameMapCell n : tColumns) {
				if(n.getName().equals(pColumn)){
					return s;
				}
			}
		}
		return null;
	}
	
	public List<NameMapCell> getColumns(String pName){
		List<NameMapCell> tOut = null;
		if(map.containsKey(pName)){
			tOut = map.get(pName);
		}
		return tOut;
	}
	
	/**
	 * 判斷是否相同
	 * @param pNameMap
	 * @return
	 */
	public boolean isSame(NameMap pNameMap) {
		Map<String, List<NameMapCell>> tBaseMap    = map;
		Map<String, List<NameMapCell>> tCurrentMap = pNameMap.map;
		if(tBaseMap.size() != tCurrentMap.size()) return false;
		for (List<NameMapCell> n : tBaseMap.values()) {
			boolean tSame = false;
			for (List<NameMapCell> c : tCurrentMap.values()) {
				if(isSame(n,c)){
					tSame = true;
				}
			}
			if(!tSame) return tSame;
		}
		return true;
	}

	private boolean isSame(List<NameMapCell> n, List<NameMapCell> c) {
		if(n.size()!=c.size()) return false;
		Collections.sort(n);
		Collections.sort(c);
		for (int i = 0; i < n.size(); i++) {
			if(!n.get(i).equals(c.get(i))) return false;
		}
		return true;
	}

	/**
	 * 本身減去傳進來的 (相同結構時才可以相減)
	 * @param pNameMap
	 * @return
	 */
	public Map<String,List<NameMapCell>> getSubstract(NameMap pNameMap) {
		Map<String, List<NameMapCell>> tOut = new HashMap<String, List<NameMapCell>>();
		Map<String, List<NameMapCell>> tBaseMap = map;
		Map<String, List<NameMapCell>> tCurrentMap = pNameMap.map;
		for (String s : tBaseMap.keySet()) {
			if(!tCurrentMap.containsKey(s)){ 
				tOut.put(s, tBaseMap.get(s));
				continue;
			}
			List<NameMapCell> tBaseColumns    = tBaseMap.get(s);
			List<NameMapCell> tCurrentColumns = tCurrentMap.get(s);
			if(tBaseColumns.size() != tCurrentColumns.size()){
				tOut.put(s, tBaseMap.get(s));
				continue;
			} 
			for (NameMapCell c : tBaseColumns) {
				if(!tCurrentColumns.contains(c)) {
					tOut.put(s, tBaseMap.get(s));
					break;
				}
			}
		}
		return tOut;
	}
	
	@Override
	public String toString() {
		return "[" + map + "]";
	}
}